//
//  RecommendViewController.m
//  CarHome
//
//  Created by 王建男 on 14-9-17.
//  Copyright (c) 2014年 WJN_work@163.com. All rights reserved.
//

#import "RecommendViewController.h"
//Models
#import "ScrollModel.h"
//ThirdPart
#import "UIButton+WebCache.h"
//ThirdControl
#import "SMPageControl.h"
//ViewController
#import "ChannelVC.h"
#import "RecommendWebVC.h"
#import "SearchBarVC.h"
//左抽屉
#import "MMDrawerController.h"
#import "UIViewController+MMDrawerController.h"

#import "MODropAlertView.h"

//button的类型枚举
enum buttonTag {
    Last = 100,//最新
    News,//新闻
    Evaluation,//评测
    Price,//行情
    UseCar,//用车
    Civilization,//文化
    Refit,//改装
    Travel,//游记
    Technology,//技术
    Movie,//视频
    Persuader,//说客
    ShopGuide//导购
};

@interface RecommendViewController ()<UIScrollViewDelegate>
{
    UIScrollView *_scrollView; //为解决版本问题加的ScrollView,放在最底层
    
    UIScrollView *_scrollView_sub;//广播滚动条
    NSMutableArray *_arrScroll;//滚动视图数据
    
    SMPageControl *_myPageControl;//圆点
    int _numberOfPage;//圆点数
    
    UIImageView *_channelView; //频道的背景
}
@end

@implementation RecommendViewController
- (void)dealloc
{
    [_arrScroll release];
    _arrScroll = nil;
    [super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _arrScroll = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = myColor_dark;
    self.navigationController.navigationBar.barTintColor = myColor_dark;
    self.tabBarController.tabBar.barTintColor = myColor_dark;//tabBar颜色

    //nav的标题
    self.navigationItem.title = @"推  荐";
    NSDictionary * dic=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, [UIFont systemFontOfSize:26.0], NSFontAttributeName, nil];
    [self.navigationController.navigationBar setTitleTextAttributes:dic];
    //nav的左按钮
    UIButton *buttonLeft_rec_navBar = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonLeft_rec_navBar.frame = CGRectMake(0, 0, 50, 45);
    [buttonLeft_rec_navBar setImage:[UIImage imageNamed: @"Nav_User.png"] forState:UIControlStateNormal];
    [buttonLeft_rec_navBar addTarget:self action:@selector(navLeft:) forControlEvents:UIControlEventTouchUpInside];
    buttonLeft_rec_navBar.imageEdgeInsets = UIEdgeInsetsMake(-2, -15, 2, 15);
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonLeft_rec_navBar];
    //nav的右按钮
    UIButton *buttonRight_rec_navBar = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonRight_rec_navBar.frame = CGRectMake(0, 0, 90, 45);
    [buttonRight_rec_navBar setImage:[UIImage imageNamed:@"Nav_Seacher.png"] forState:UIControlStateNormal];
    [buttonRight_rec_navBar addTarget:self action:@selector(navRight:) forControlEvents:UIControlEventTouchUpInside];
    buttonRight_rec_navBar.imageEdgeInsets = UIEdgeInsetsMake(-2, 15, 2, -15);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonRight_rec_navBar];
    // Do any additional setup after loading the view.
    
    //创建视图
    [self createScrollView];
    [self createMyPageControl];
    [self createChannelView];
    
    /*网络请求
     *1.滚动视图的网络请求
     */
    if ([NetUrl isExistencenetNot]) {
        [self startScrollNet];
    } else {
        
        MODropAlertView *alertView = [[MODropAlertView alloc]initDropAlertWithTitle:@"温馨提示"
                                                                        description:@"网络连接失败,请查看网络是否连接正常！"
                                                                      okButtonTitle:@"确定"];
        alertView.delegate = self;
        [alertView setBackgroundColor:[UIColor colorWithWhite:0.1 alpha:0.6]];
        [alertView show];
    }
}

#pragma mark -
#pragma mark nav左侧点击事件
- (void)navLeft:(id)sender
{
    //左抽屉
    [self.tabBarController.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}
#pragma mark nav右侧搜索功能
- (void)navRight:(id)sender
{
    SearchBarVC *search = [[SearchBarVC alloc] init];
    [self presentViewController:search animated:YES completion:^{
        
    }];
    [search release];
}

#pragma mark -
#pragma mark NetURL
- (void)startScrollNet
{
    /*
     *滚动视图的网络数据请求
     *1.for循环,创建UIImageView的滚动视图
     */
    
    
    if ([NetUrl isExistencenetWork]) {
        
        MODropAlertView *alertView = [[MODropAlertView alloc]initDropAlertWithTitle:@"温馨提示"
                                                                        description:@"当前网络为3G网络,建议切换至WIFI状态！"
                                                                      okButtonTitle:@"确定"];
        alertView.delegate = self;
        [alertView setBackgroundColor:[UIColor colorWithWhite:0.1 alpha:0.6]];
        [alertView show];
    }
    
    [NetUrl connect:ScrollURL parmater:nil Block:^(NSData *data) {
        NSDictionary *dictionary = (NSDictionary *)data;
        NSMutableDictionary *dic = [dictionary objectForKey:@"result"];
        //1.滚动视图的正常数据
        ScrollModel *scrollModel = [ScrollModel returnModelArrayWithDic: dic];
        //2.滚动视图推广数据
        [NetUrl connect:GeneralizeURL parmater:nil Block:^(NSData *data) {
            NSDictionary *dictionary = (NSDictionary *)data;
            NSMutableDictionary *dic = [dictionary objectForKey:@"result"];
            ScrollModel *scrollGeneralize = [ScrollModel returnArrayWithGeneralizeFocus:dic];
            if ([scrollGeneralize.focusimg count] != 0) {
                for (FoucusImageModel *image in scrollGeneralize.focusimg) {
                [_arrScroll insertObject:image atIndex:image.image_index - 1];
                }
            }
            while([_arrScroll count] > 6) {
                [_arrScroll removeLastObject];
            }
            NSMutableArray *arrFocus = [NSMutableArray arrayWithArray:_arrScroll];
            [_arrScroll removeAllObjects];
            [_arrScroll addObject:[arrFocus firstObject]];
            [_arrScroll addObjectsFromArray:arrFocus];
            [_arrScroll addObject:[arrFocus lastObject]];
            int tag = 1000;
            for (int i = 0; i < [_arrScroll count]; i++) {
                UIButton *imageButton = [[UIButton alloc] initWithFrame:CGRectMake(320 * i, 0, 320, 160)];
                FoucusImageModel *model =[_arrScroll objectAtIndex:i];
                imageButton.tag = tag;
                [imageButton sd_setBackgroundImageWithURL:[NSURL URLWithString:model.image_smallPic]  forState:UIControlStateNormal];
                [imageButton addTarget:self action:@selector(scrollViewButtonClick:) forControlEvents:UIControlEventTouchUpInside];
                [_scrollView_sub addSubview:imageButton];
                tag++;
            }
            _scrollView_sub.contentSize = CGSizeMake(320 * [_arrScroll count], 0);
            _scrollView_sub.contentOffset = CGPointMake(320, 0);//初始偏移量
            // 设置pagecontol的个数
            _numberOfPage = (int)([_arrScroll count] - 2);
            _myPageControl.numberOfPages = _numberOfPage;
            
        }];
        if ([scrollModel.focusimg count] != 0) {
            [_arrScroll addObjectsFromArray:scrollModel.focusimg];
        }
    }];
}


#pragma mark -
#pragma mark createView
- (void)createScrollView
{
    //铺底的ScrollView
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64)];
    [self.view addSubview:_scrollView];
    _scrollView.contentSize = CGSizeMake(0,456);
    [_scrollView release];
    
    //广告滚动条
    _scrollView_sub = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 160)];
    [_scrollView_sub setPagingEnabled:YES];
    [_scrollView_sub setBounces:NO];
    _scrollView_sub.showsVerticalScrollIndicator = NO;
    [_scrollView_sub setShowsHorizontalScrollIndicator:YES];
    _scrollView_sub.backgroundColor = [UIColor grayColor];
    _scrollView_sub.delegate = self;
    [_scrollView addSubview:_scrollView_sub];
    
    [_scrollView_sub release];
    
    // 创建NSTimer定时器
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(changeTimer:) userInfo:nil repeats:YES];
    [timer fire];
}
- (void)createChannelView
{
    //频道背景色
    _channelView = [[UIImageView alloc] initWithFrame:CGRectMake(0, _scrollView_sub.frame.size.height, self.view.frame.size.width, 296)];
    [_channelView setBackgroundColor:[UIColor whiteColor]];
    _channelView.image = [UIImage imageNamed:@"Channel_Background.png"];
    _channelView.userInteractionEnabled = YES;
    [_scrollView addSubview:_channelView];
    
    //12个频道button
    NSArray *arr_imageName = @[@"Button_New.png", @"Button_Notepad.png",@"Button_Chart.png",@"Button_Price.png",@"Button_useCar.png",@"Button_Civilization.png",@"Button_Modify.png",@"Button_Travel.png",@"Button_Origrinate.png",@"Button_Movies.png",@"Button_Lobbyist.png",@"Button_Serve.png",];
    int channel_rec_tag = 100;
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 3; j++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(5 + 105 * j, 3 + 73 * i, 100, 70);
            [button setImage: [UIImage imageNamed:[arr_imageName objectAtIndex:i * 3 + j]] forState:UIControlStateNormal];
            button.tag = channel_rec_tag;
            channel_rec_tag++;
            [button addTarget:self action:@selector(enterChannelVC:) forControlEvents:UIControlEventTouchUpInside];
            [_channelView addSubview:button];
        }
    }
    [_channelView release];
}
- (void)createMyPageControl
{
    _myPageControl = [[SMPageControl alloc] initWithFrame:CGRectMake(0, _scrollView_sub.frame.size.height - 8, self.view.frame.size.width, 5)];
    _myPageControl.pageIndicatorMaskImage = [UIImage imageNamed:@"page_defult.png"];
    _myPageControl.pageIndicatorTintColor = [[UIColor whiteColor] colorWithAlphaComponent:0.95f];
    _myPageControl.currentPageIndicatorTintColor = [UIColor blackColor];
    [_scrollView addSubview:_myPageControl];
    [_myPageControl release];
    
}
#pragma mark -
#pragma mark scrollDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (_scrollView_sub.contentOffset.x == 0) {
        _scrollView_sub.contentOffset = CGPointMake(_numberOfPage * 320, 0);
    } else if (_scrollView_sub.contentOffset.x == (_numberOfPage + 1) * 320) {
        _scrollView_sub.contentOffset = CGPointMake(320, 0);
    }
    [UIView animateWithDuration:0.5 animations:^{
        _myPageControl.currentPage = scrollView.contentOffset.x / scrollView.frame.size.width - 1;
    }];
}
#pragma mark 轮播区的点击事件
- (void)scrollViewButtonClick:(UIButton *)button
{
    RecommendWebVC *recommnedWeb = [[RecommendWebVC alloc] init];
    FoucusImageModel *model = [_arrScroll objectAtIndex:button.tag - 1000];
    if ([model.image_mediatype intValue] == 0) {
        [recommnedWeb setWebUrl:model.image_urlPath];
    } else if ([model.image_mediatype intValue] == 2) {//原创视频
        [recommnedWeb setWebUrl:[NSString stringWithFormat: videosContentURL, [model.image_ID intValue]]];
    } else if ([model.image_mediatype intValue] == 3) {
        [recommnedWeb setWebUrl:[NSString stringWithFormat: videosContentURL, [model.image_ID intValue]]];
    }else if ([model.image_mediatype intValue] == 5 || [model.image_mediatype intValue] == 4) {
        [recommnedWeb setWebUrl:[NSString stringWithFormat: forumContentURL, [model.image_ID intValue]]];
    } else if ([model.image_mediatype intValue] == 1) {//新闻
        [recommnedWeb setWebUrl:[NSString stringWithFormat:NewsContentURL, [model.image_ID intValue]]];
    }
    [self.navigationController pushViewController:recommnedWeb animated:YES];
    [recommnedWeb release];
}

#pragma mark -
#pragma mark timerChangeMethod
- (void)changeTimer:(id)sender
{
    _scrollView_sub.contentOffset = CGPointMake(_scrollView_sub.contentOffset.x + 320, 0);
    if (_scrollView_sub.contentOffset.x == 0) {
        _scrollView_sub.contentOffset = CGPointMake(_numberOfPage * 320, 0);
    } else if (_scrollView_sub.contentOffset.x == (_numberOfPage + 1) * 320) {
        _scrollView_sub.contentOffset = CGPointMake(320, 0);
    }
    [UIView animateWithDuration:0.5 animations:^{
        _myPageControl.currentPage = _scrollView_sub.contentOffset.x / _scrollView_sub.frame.size.width - 1;
    }];
}
#pragma mark buttonChannelclickMethod
- (void)enterChannelVC:(id)sender
{
    /*
     *1.判断是那个button的点击事件
     *2.如果是最新,新闻,评测,行情,用车,文化,改装,游记,技术,导购同一类数据类型,用[returnModelArrayWithNewsList:]方法解析数据
     *3.否则,是视频数据结构,用[returnArrayWithMovie:]方法解析数据
     *4.否则,是说客数据结构,用[returnArrayPersuader:]方法解析数据
     */
    //1.
    UIButton *button = (UIButton *)sender;
    ChannelVC *channel = [[ChannelVC alloc] init];
    NSString *strURL = [[NSString alloc] init];
    if (button.tag == Movie || button.tag == Persuader) {
        //3 & 4.
        if (button.tag == Movie) {
            strURL = MovieURL;
        }
        if (button.tag == Persuader) {
            strURL = PersuaderURL;
        }
        [NetUrl connect:strURL parmater:nil Block:^(NSData *data) {
            NSDictionary *dictionary = (NSDictionary *)data;
            NSMutableDictionary *dic = [dictionary objectForKey:@"result"];
            if ([strURL  isEqualToString: MovieURL]) {
                ScrollModel *movie = [ScrollModel returnArrayWithMovie:dic];
                [channel sendData:movie.vediosList url:strURL title:@"视  频"];
            }
            if ([strURL isEqualToString:PersuaderURL]) {
                ScrollModel *persuader = [ScrollModel returnArrayWithPersuader:dic];
                [channel sendData:persuader.shuoKeList url:strURL title:@"说  客"];
            }
        }];
    } else {
    //新闻,评测,行情,用车,文化,改装,游记,技术,导购
    int value = 0;
    int type = 0;
    NSString *title = @"";
    switch (button.tag) {
        case Last:
        {
            type = 2;
            title = @"最  新";
        }
            break;
        case News:
        {
            type = 1;
            value = 1;
            title = @"新  闻";
        }
            break;
        case Evaluation:
        {
            type = 1;
            value = 3;
            title = @"评  测";
        }
            break;
        case Price:
        {
            type = 1;
            value = 2;
            title = @"行  情";
        }
            break;
        case UseCar:
        {
            type = 1;
            value = 82;
            title = @"用  车";
        }
            break;
        case Civilization:
        {
            type = 1;
            value = 97;
            title = @"文  化";
        }
            break;
        case Refit:
        {
            type = 1;
            value = 107;
            title = @"改  装";
        }
            break;
        case Travel:
        {
            type = 1;
            value = 100;
            title = @"游  记";
        }
            break;
        case Technology:
        {
            type = 1;
            value = 102;
            title = @"技  术";
        }
            break;
        case ShopGuide:
        {
            type = 1;
            value = 60;
            title = @"导  购";
        }
            break;
        default:
            break;
    }
    //2.
    strURL = [NSString stringWithFormat:NewsListURL,type,value];
    [NetUrl connect:strURL parmater:nil Block:^(NSData *data) {
        NSDictionary *dictionary = (NSDictionary *)data;
        NSMutableDictionary *dic = [dictionary objectForKey:@"result"];
        ScrollModel *newsListModel = [ScrollModel returnModelArrayWithNewsList:dic];
        [channel sendData:newsListModel.newslist url:strURL title:title];
    }];
    }
    [self.navigationController pushViewController:channel animated:YES];
    [channel release];

}



#pragma mark -
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
